//
//  SaleAfter.swift
//  smosky
//
//  Created by zhuxietong on 2018/8/8.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation
import AsyncDisplayKit
import soapp
import Eelay


public enum SaleAfterType:String{
    case returnMoney = "0"
    case returnGoods = "1"
    case changeGoods = "2"
    
    public var name:String{
        get{
            switch self {
            case .changeGoods:
                return "换货".loc
            case .returnGoods:
                return "退货".loc
            case .returnMoney:
                return "退款".loc
            }
        }
    }
    
    
    public static func validAfterSeverGoods(order:NSMutableDictionary)->NSMutableArray{
        let goods = DataNode.path(node: "order.goods", order, value: NSMutableArray())
        let __goods = NSMutableArray()
        goods.list { (one:NSMutableDictionary, i) in
            if one["canrefund",false.tag] == true.tag
            {
                __goods.add(one)
            }
        }
        return __goods
    }
    public static func validSeverFor(order:NSMutableDictionary) ->[SaleAfterType] {
        let goods = DataNode.path(node: "order.goods", order, value: NSMutableArray())
        if goods.count > 0
        {
            return [.returnGoods,.returnMoney,.changeGoods]
        }
        return [SaleAfterType]()
    }
    
    public var icon:String{
        switch self {
        case .changeGoods:
            return "shouhou_huanhuo_03"
        case .returnGoods:
            return "shouhou_tuohuo_01"
        case .returnMoney:
            return "shouhou_tuihuotuikuan_02"
        }
    }
    
    public var item:[String:String]{
        get{
            switch self {
            case .returnMoney:
                return ["name":"退款".loc,"desc":"未收到货,货物损坏,或卖家协商同意前提下".loc,"icon":self.icon,"id":self.rawValue]
            case .changeGoods:
                return ["name":"换货".loc,"desc":"已收到货,需要换货".loc,"icon":self.icon,"id":self.rawValue]
            default:
                return ["name":"退货".loc,"desc":"已收到货,需要退掉货物".loc,"icon":self.icon,"id":self.rawValue]
            }
        }
    }
}



public extension SaleAfter{
    
   
    
    static func applySaleAfter(order:NSMutableDictionary,at controller:UIViewController?)
    {
        let ctr = AfterApplyStep1()
        ctr.controller = controller
        ctr.order = order
        controller?.present(ctr, animated: false, completion: nil)
    }
    
    
    class AfterListCell:JoCellNode{
        
    }
}



public struct SaleAfter{
    
    
    class LogisticsCell: JoCellNode {
        let iconV = ASImageNode()
        let noL = ASTextNode2()
        let logistL = ASTextNode2()
        let timeL = ASTextNode2()
        
        let emptyNode = ASDisplayNode()
        let moreIconV = ASImageNode()

        
        override func cellTouch() {
            if haveExpress{
                let ctr = LogisticsCtr()
                let wuliuKey = mo.model["expkey","expresses"]

                ctr.mo.model = mo.model.any(nodes: "__model.\(wuliuKey)", default: NSMutableDictionary())
                mo.controller?.navigationController?.pushViewController(ctr, animated: true)
            }
        }
        
        
        override func mo_model_reload() {
            backgroundColor = ._background
            internalCellTouch = true

            let wuliuKey = mo.model["expkey","expresses"]
            let wuliu = DataNode.path(node: "__model.\(wuliuKey)", mo.model, value: NSMutableDictionary())
            
            let expresscom = wuliu.possible("expresscom","rexpresscom", default: "快递".loc)
            var expresssn = wuliu.possible("expresssn","rexpresssn", default: "")
            if expresssn.len > 0
            {
                expresssn = "(\(expresssn))"
            }
            

            if haveExpress{
                let time = wuliu["time",""]
                let step = wuliu["step",""]

                noL.maximumNumberOfLines = 1;logistL.maximumNumberOfLines = 2
                noL.attributedText = "\(expresscom) \(expresssn)".ui.font13.cl_333.astring
                logistL.attributedText = "\(time) \(step)".ui.font12.lineSpace(5).cl_666.astring
                iconV.image = UIImage(named: "shouhou_02")
                moreIconV.image = UIImage(named: "more_indicator0")
            }
            else{
                noL.maximumNumberOfLines = 1;
                logistL.maximumNumberOfLines = 1
                noL.attributedText = "\(expresscom) \(expresssn)".ui.font12.cl_333.astring
                iconV.image = UIImage(named: "shouhou_02")
                moreIconV.image = UIImage(named: "more_indicator0")

            }
        }
        
        var haveExpress:Bool
        {
            get{
                let key = mo.model["expkey",""]
                let step = mo.model["__model.\(key).step",""]
                
                return step.len > 0
            }
        }
        
        
        override func specGetter() -> _Spec {
            var specs:[_Spec] = [noL.Spec]

            if haveExpress{
                specs.append(logistL.Spec)
            }
            return _Spec.stack(["h|10",&-.center,_nowrap,[13,AppTheme.edge]], childs: [
                iconV["16",25],
                .stack(["v|5",&-.stretch,_justfy(.space_between),_shrink(1),_grow(1)], childs: specs),
                moreIconV["14",8]
            ])
           
//            if haveExpress{
//                    var specs:[_Spec] = [noL.Spec]
//                    specs.append(logistL.Spec)
////                    specs.append(timeL.Spec)
//
//                return _Spec.stack(["h|10",&-.center,_nowrap,[13,AppTheme.edge]], childs: [
//                    iconV["16",25],
//                    .stack(["v",&-.stretch,_justfy(.space_between),_shrink(1),_grow(1)], childs: specs),
//                    moreIconV["14",8]
//                ])
//            }
//            else{
//                return .wrapper(emptyNode[0])
//            }
        }
    }
    
    
    
    class InfoKit: JoTouchNode {
        let nameL = ASTextNode2()
        let valueL = ASTextNode2()
        override func specGetter() -> _Spec {
            return .stack(["h|10",_nowrap,[0,0]], childs: [
                nameL[60],
                valueL[_shrink(1)],
                ])
        }
        override func mo_model_reload() {
            let title = mo.model["title",""] + ":"
            nameL.attributedText = title.ui.color(color: ._foreground).font12.lineSpace(5).astring
            valueL.attributedText = mo.model["value",""].ui.cl_444.lineSpace(5).font12.astring
            self.isUserInteractionEnabled = false
        }
    }
    
    class ImgKit: ASScanSupportKit {
        override var itemSize:CGSize{
            get{
                let num:CGFloat = Swidth > 321 ? 5 : 4
                
                let space_w = space.X
                let width:CGFloat = Swidth - 2.0 * AppTheme.edge - space_w * (num - 1.0)
                let w:CGFloat = width/num - 4
                
                return CGSize(width: w, height: w)
            }
        }
    }
    
    class ApplayInfoCell: ASImagesScanCell<ImgKit>{
        let infoV = JoRuleNode<InfoKit>()
        let markL = ASTextNode2()
        
        var type:SaleAfterType = .returnGoods
        
        
        override func addLayoutRules() {
            super.addLayoutRules()
            backgroundColor = ._background
            infoV.containerConfig = {
                spec in
                spec.alignItems = ASStackLayoutAlignItems.stretch
                spec.direction = ASStackLayoutDirection.vertical
            }
        }
        
        override func mo_model_reload() {

            let object = DataNode.path(node: "__model", mo.model, value: NSMutableDictionary())
//            mo.model["imgs"] = [
//                __goods.one_str,
//                __goods.one_str,
//                __goods.one_str,
//                __goods.one_str,
//            ].mutable_array
            
            
            let list = DataNode.path(node: "imgs", object, value: NSMutableArray())
            var imgs = [String]()
            list.list { (one:String, i) in
                imgs.append(one)
            }
            
            let imgs_list = imgs.map { (str) -> [String:Any] in
                return ["img":str]
            }
            
            
            
            
            imgsView.mo.model = [
                "list":imgs_list
                ].mutable_dictionary
            
            var images = [EeImageResourceModel]()
            for one in imgs{
                let a = EeImageResourceModel(url: one)
                images.append(a)
            }
            self.browerModels = images
            
            separatorHeight = 8

            
            separatorColor = .clear
            
            infoV.nodePath = "options"
            
            let price = object[float:"applyprice",0].price_display
            let goods_num = DataNode.path(node: "goods", object, value: NSMutableArray()).count
            infoV.mo.model = [
                "options":[
                    ["title":"[XX]编号".replaceVars(values: type.name),"value":object["refundno",""]],
                    ["title":"退款金额".loc,"value":"¥ [XX]".replaceVars(values: price)],
                    ["title":"[XX]商品".replaceVars(values: type.name),"value":"\(goods_num) \("件".loc)"],
                    ["title":"申请时间".loc,"value":stampToTime(object["createtime",""])["yyyy-MM-dd HH:mm"]],
                    ["title":"退款原因".loc,"value":object["reason",""]],
                ]
            ].mutable_dictionary
            
            
            markL.attributedText = "\("备注信息".loc):     ".ui.bfont12.color(hex: "#DE3A23").lineSpace(8).astring + object["content",""].ui.font12.color(color: ._foreground).lineSpace(8).astring
            
            
            
            
            
            //            let time = stampToTime(mo.model["createtime",""])["yyyy-MM-dd HH:mm"]
            
        }
        
        override func specGetter() -> _Spec {
            
            let specs:[_Spec] = [infoV.Spec,markL.Spec,imgsView.Spec]
            let root = _Spec.stack(["v|10",&-.stretch,[AppTheme.edge,AppTheme.edge]], childs: specs)
    
            return root
        }
    }
}

extension SaleAfter{
    class TitleCell: JoCellNode {
        let infoL = ASTextNode2()
        
        override func mo_model_reload() {
            view.backgroundColor = ._cellBackground
            infoL.attributedText = mo.model["title","退款信息".loc].ui.bfont14.color(color: ._foreground).astring
        }
        
        override func specGetter() -> _Spec {
            return .stack(["h|10",&-.center,[12,AppTheme.edge]], childs: [
                infoL.Spec
                ])
        }
    }
    
    class GoodsCell: Goods.OrderListCell {
        
        class SellerNode: Goods.OrderListCell.SellerNode1 {
            override func mo_model_reload() {
                
            }
        }
        override func willLayoutRules() {
            goodsV.nodePath = "goods"
        }
        override func addLayoutRules() {
            sellerV = Goods.OrderListCell.SellerNode1()
            sellerV.statusL.alpha = 0
            view.backgroundColor = ._cellBackground
        }
        
        override func mo_model_reload() {
            
            super.mo_model_reload()
            sellerV.mo.model = DataNode.path(node: "__model.merch", mo.model, value: NSMutableDictionary())
            
        }
        
        override func specGetter() -> _Spec {
            let spec = _Spec.stack(["v",_shrink(1),_justfy(.space_between),&-.stretch], childs: [
                sellerV.Spec,
                goodsV.Spec,
            ])
            return spec
            
        }
    }
    
    class NoteCell: JoCellNode {
        let pointV = ASDisplayNode()
        let infoL = ASTextNode2()
        
        override func mo_model_reload() {
            backgroundColor = ._background
            
            self.separatorHeight = TP.separatorHeight
            pointV.view.bsui.background(hex: "#888").set(radius: 3.5, width: nil, color: nil)
            infoL.attributedText = "商家同意或者超时未处理，系统将退款给您".loc.ui.font13.color(color: .color(light: "#666", dark: "#aaa")).astring
        }
        
        override func specGetter() -> _Spec {
            return .stack(["h|10",&-.center,[12,AppTheme.edge]], childs: [
                pointV["7",7],infoL.Spec
                ])
        }
    }
    
    class HistoryCell: JoCellNode {
        let nameL  = ASTextNode2()
        let moreIconV = ASImageNode()
        
        
        override func cellTouch() {
            let ctr = ConsultHistoryCtr()
            ctr.mo.model = self.mo.model
            mo.controller?.navigationController?.pushViewController(ctr, animated: true)
        }
    
        override func mo_model_reload() {
            internalCellTouch = true
            backgroundColor = ._background
            
            self.separatorColor = UIColor._separator
            self.separatorHeight = TP.separatorHeight
            nameL.attributedText = mo.model["title",""].ui.font13.color(color: ._foreground).astring
            moreIconV.image = UIImage(named: "more_indicator0")
        }
        
        override func specGetter() -> _Spec {
            return .stack(["h|10",&-.center,_justfy(.space_between),[12,AppTheme.edge]], childs: [
                nameL.Spec,moreIconV["14",8]
            ])
        }
    }
}
